package com.ws.q1.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ws.q1.bean.User;
import com.ws.q1.conifg.Res;
import com.ws.q1.service.HouTaiUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/houtaiuser")
public class HouTaiUserController {
    @Autowired
    private HouTaiUserService houTaiUserService;

    @RequestMapping("/zeng")
    public String add(User user, MultipartFile image) throws IOException {
        System.out.println(user);
        // 检查用户名是否已存在
        if (houTaiUserService.isUsernameExists(user.getName())) {
            return "denglu/flie";
        }
        if (image.getSize() > 0) {
            String replace = UUID.randomUUID().toString().replace("-", "");
            String fileName = replace + "." + image.getOriginalFilename().split("\\.")[1];
            user.setTou(fileName);
            image.transferTo(new File(Res.fileDir + fileName));
        } else {
            user.setTou("e18aa2ce37c243aaa8cdc0d99d1c74c5.jpg");
        }
        String s = DigestUtils.md5DigestAsHex(user.getPass().getBytes());
        user.setPass(s);
        int add = houTaiUserService.add(user.getName(), user.getPass(), user.getPhone(), user.getTou());
        if (add > 0) {
        }
        return "redirect:/houtaiuser/list";
    }

    @RequestMapping("/tiao")
    public String tiao() {
        return "user/add";
    }

    @RequestMapping("/shan")
    public String shan() {
        return "redirect:houtaiuser/delete";
    }

    // 查看
    @RequestMapping("/list")
    public String list(Model model, @RequestParam(defaultValue = "1") int currentPage, @RequestParam(required = false) String name) {
        int pageSize = 5; // 每页显示的记录数
        PageHelper.startPage(currentPage, pageSize); // 确保在调用 Mapper 层方法之前调用
        List<User> list;
        PageInfo<User> pageInfo;
        if (name != null && !name.isEmpty()) {
            list = houTaiUserService.getUsersByName(name);
            pageInfo = new PageInfo<>(list);
        } else {
            list = houTaiUserService.getAllUsers();
            pageInfo = new PageInfo<>(list);
        }

        // 计算分页范围
        int totalPages = pageInfo.getPages();
        int startPage = Math.max(1, currentPage - 4);
        int endPage = Math.min(totalPages, currentPage + 4);

        // 打印分页信息以进行调试
        System.out.println("当前页: " + pageInfo.getPageNum());
        System.out.println("总页数: " + pageInfo.getPages());
        System.out.println("总记录数: " + pageInfo.getTotal());
        System.out.println("每页显示记录数: " + pageInfo.getPageSize());

        model.addAttribute("list", list);
        model.addAttribute("startPage", startPage);
        model.addAttribute("endPage", endPage);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("user", name); // 传递查询参数到前端
        return "user/list";
    }

    // 删除
    @RequestMapping("/delete")
    public String delete(Integer id) {
        int result = houTaiUserService.deleteById(id);
        return "redirect:/houtaiuser/list";
    }

    @RequestMapping("/update")
    public String update(User user, MultipartFile image) throws IOException {
        User existingUser = houTaiUserService.huixian(user.getId());
        if (user.getPass() != null && !user.getPass().isEmpty()) {
            String s = DigestUtils.md5DigestAsHex(user.getPass().getBytes());
            user.setPass(s);
        } else {
            user.setPass(existingUser.getPass());
        }
        if (image != null && !image.isEmpty()) {
            String replace = UUID.randomUUID().toString().replace("-", "");
            String fileName = replace + "." + image.getOriginalFilename().split("\\.")[1];
            user.setTou(fileName);
            image.transferTo(new File(Res.fileDir + fileName));
        } else {
            // 如果没有上传新头像，保持原有头像
            user.setTou(existingUser.getTou());
        }
        houTaiUserService.update(user.getId(), user);
        return "redirect:/houtaiuser/list";
    }



    // 回显
    @RequestMapping("/huixian")
    public String huixian(Integer id, Model model) {
        System.out.println(id);
        User huixian = houTaiUserService.huixian(id);
        System.out.println(huixian);
        model.addAttribute("huixian", huixian);
        return "user/update";
    }
}
